package com.example.myblog.utils;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.Random;

public class MD5 {

    public static String generate(String res) {
        Random r = new Random();
        StringBuilder stringBuilder = new StringBuilder(16);
        stringBuilder.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = stringBuilder.length();
        if (len < 16) {
            for (int i = 0;i < 16-len;i++) {
                stringBuilder.append("0");
            }
        }
        String salt = stringBuilder.toString();
        res = md5Hex(res + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i+=3) {
            cs[i] = res.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i+1] = c;
            cs[i+2] = res.charAt(i / 3 * 2 + 1);

        }
        return new String(cs);
    }

    public static boolean verify(String password,String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i+=3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(password + salt).equals(new String(cs1));
    }

    public static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String pass1 = generate("yx1234567890");
        System.out.println(pass1);
        System.out.println(verify("yx1234567890",pass1));


        String pass2 = generate("yx1234567890");
        System.out.println(pass2);
        System.out.println(verify("yx1234567890",pass2));
    }

}
